//
// BonusLife.cpp for nibbler in /home/lefebv_w//workspace/cpp/nibbler/googleCode
// 
// Made by damien lefebvre
// Login   <lefebv_w@epitech.net>
// 
// Started on  Fri Mar 22 01:57:38 2013 damien lefebvre
// Last update Sun Mar 24 13:26:36 2013 tristan moreau
//

#include	"BonusLife.hh"

BonusLife::BonusLife(void)
  : m_type(IGraphicLibrary::BONUS), m_pos_x(0), m_pos_y(0), m_img(IGraphicLibrary::IMG_BONUSLIFE), m_dir(IGraphicLibrary::DOWN), m_activ(false), m_lastmove(0), m_framerate(3)
{}

void		BonusLife::generatePosition(t_frame frame, std::vector< std::vector<Case *> > const & map, Snake const & snake)
{
  bool		posok;

  if (m_activ == false)
    {
      posok = false;
      for (unsigned int i = 0; posok == false && i < map.size(); i++)
	{
	  for (unsigned int j = 0; posok == false && j < map[i].size(); j++)
	    {
	      if (map[i][j]->getType() == IGraphicLibrary::EMPTY &&
		  snake.checkIntersection(i, j) == false)
		{
		  m_pos_x = i;
		  m_pos_y = j;
		  posok == true;
		}
	     }
	}
      m_dir = IGraphicLibrary::UP;
      m_lastmove = 0;
    }
}

void		BonusLife::draw(t_frame frame, IGraphicLibrary & graph) const
{
    graph.draw(m_pos_x, m_pos_y, m_img);
}

bool		BonusLife::checkSnakePosition(t_frame frame, Snake const & snake) const
{
  if (snake.getPosX() == m_pos_x && snake.getPosY() == m_pos_y)
    return (true);
  return (false);
}

void		BonusLife::move(t_frame frame, std::vector< std::vector<Case *> > const & map, Snake const & snake)
{
  unsigned int			new_pos_x;
  unsigned int			new_pos_y;
  IGraphicLibrary::e_Direction	new_dir;
  bool				newpos;

  if (frame - m_lastmove >= m_framerate)
    {
      newpos = false;
      new_dir = m_dir;
      new_pos_y = m_pos_y;
      new_pos_x = m_pos_x;
      for (unsigned int i = 0; newpos == false && i < 4; i++)
	{
	  switch (new_dir)
	    {
	    case IGraphicLibrary::UP :
	      new_pos_y = m_pos_y - 1;
	      break;
	    case IGraphicLibrary::DOWN :
	      new_pos_y = m_pos_y + 1;
	      break;
	    case IGraphicLibrary::LEFT :
	      new_pos_x = m_pos_x - 1;
	      break;
	    case IGraphicLibrary::RIGHT :
	      new_pos_x = m_pos_x + 1;
	      break;
	    }
	  if (new_pos_x < map.size() && new_pos_y < map[new_pos_x].size() &&
	      map[new_pos_x][new_pos_y]->getType() == IGraphicLibrary::EMPTY &&
	      snake.checkIntersection(new_pos_x, new_pos_y) == false)
	    newpos = true;
	  else
	    new_dir = (IGraphicLibrary::e_Direction)((new_dir + 1) % 4);
	}
      if (newpos == true)
	{
	  m_pos_x = new_pos_x;
	  m_pos_y = new_pos_y;
	  m_dir = new_dir;
	}
      m_lastmove = frame;
    }
}

t_frame		BonusLife::getLastMove(void) const
{
  return (m_lastmove);
}

t_frame		BonusLife::getFrameRate(void) const
{
  return (m_framerate);
}
